<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="账号：请输入登录账号">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        type="password"
        placeholder="密码：请输入登录密码"
        show-password
        autocomplete="new-password"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <el-form-item prop="username">
    <el-input v-model="loginForm.verify" placeholder="验证码：请输入验证码">
      <template #prefix>
        <el-icon class="el-input__icon">
          <ScaleToOriginal />
        </el-icon>
      </template>
      <template #suffix>
        <ElTooltip placement="top">
          <template #content>点击刷新验证码</template>
          <ElImage :width="150" :height="25" style="cursor: pointer" :src="vercodeurl" @click="getYZM" />
        </ElTooltip>
      </template>
    </el-input>
  </el-form-item>
  <div class="login-btn">
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { ElNotification } from "element-plus";
import { loginApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { Lock, ScaleToOriginal, User, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import { UserApi } from "~/types/module/system/user";
import { encryptedDES } from "@/utils/tools";

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  name: [{ required: true, message: "请输入登录账号", trigger: "blur" }],
  pwd: [{ required: true, message: "请输入登录密码", trigger: "blur" }],
  verify: [{ required: true, message: "请输入验证码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  username: "",
  name: "",
  password: "",
  pwd: "",
  verify: "",
  timestamp: ""
});

const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      loginForm.name = encryptedDES(loginForm.username);
      loginForm.pwd = encryptedDES(loginForm.password);
      loginForm.timestamp = timestamp.value;
      await loginApi(loginForm)
        .then(async (res: any) => {
          const loginInfo = res.data;
          userStore.setToken(loginInfo.token);
          userStore.setUserInfo(loginInfo.user);
          // 2.添加动态路由
          await initDynamicRouter();
          // 3.清空 tabs、keepAlive 数据
          tabsStore.setTabs([]);
          keepAliveStore.setKeepAliveName([]);
          ElNotification({
            title: getTimeState(),
            message: `您好：${loginInfo.user.uName},欢迎回来！`,
            type: "success",
            duration: 3000
          });
          // 4.跳转到首页
          router.push(HOME_URL);
        })
        .catch((err: any) => {
          if (err) {
            loginForm.verify = "";
            getYZM();
          }
        });
    } finally {
      loading.value = false;
    }
  });
};

const vercodeurl = ref();
const timestamp = ref();
const getYZM = () => {
  timestamp.value = Math.random();
  localStorage.setItem("yzmrd", timestamp.value.toString());
  vercodeurl.value = `${import.meta.env.VITE_API_BASE_URL + UserApi.GetVerifyCode}?t=${timestamp.value}`;
};

onMounted(() => {
  getYZM();
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});

onBeforeUnmount(() => {
  document.onkeydown = null;
});
</script>

<style scoped lang="scss">
@import "../index";
</style>
